package icu.lookyousmileface.netty.simple.mylmpl;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;

/**
 * @author shenj
 * @title: NettyServer
 * @projectName NettyPro
 * @date 2020/12/4 8:09
 */
public class NettyServer {

    public static void main(String[] args) throws InterruptedException {


        EventLoopGroup mainLoop = new NioEventLoopGroup();
        EventLoopGroup workerLoop = new NioEventLoopGroup();
        try {
            ServerBootstrap severStartApplicationConfiguration = new ServerBootstrap();

            severStartApplicationConfiguration.group(mainLoop, workerLoop)
                    .channel(NioServerSocketChannel.class)
                    .option(ChannelOption.SO_BACKLOG, 128)
                    .childOption(ChannelOption.SO_KEEPALIVE, true)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            //可在此处命名一个集合用于装每个客户端的SocketChannel,然后通过Handler的ctx.channel().eventLoop().execute/Scheduler
                            //进行用户标识投放广告
                            System.out.println("新加入的客户端HasgCode；"+ch.hashCode());
                            ch.pipeline().addLast(new ServerHandler());
                        }
                    });

            System.out.println("Nio Server is ready....");

            ChannelFuture channelFuture = severStartApplicationConfiguration.bind(5566).sync();

            //添加监听器，监听事件
            channelFuture.addListener((channelFutures) ->{
                System.out.println(channelFuture.isSuccess() ? "监听5566端口成功":"监听5566端口失败");
            });

            channelFuture.channel().closeFuture().sync();


        }finally {
            mainLoop.shutdownGracefully();
            workerLoop.shutdownGracefully();
        }
    }
}
